#!/usr/bin/python
from PyQt5.QtCore import QAbstractTableModel,QModelIndex
from PyQt5.QtCore import QDateTime, QTime,Qt,QTimer,pyqtSignal,QSettings,QDir
from PyQt5.QtSql import QSqlQueryModel,QSqlQuery
from PyQt5.QtWidgets import QAction, QPushButton, QDesktopWidget,QAbstractItemView, QMainWindow, QApplication, QMessageBox, QCheckBox, QHBoxLayout,QFileDialog,QLabel, QFileDialog,QStyle,QMenu,QLineEdit
from PyQt5 import QtGui,QtCore
from PyQt5 import  QtWidgets,QtSql
import os
import re
import getpath
import config_json
import subprocess
import sys
import ui_mainw
import logging
def mylistdir(p,f):
    a=os.listdir(p)
    fs=myfind(a,f)
    return(fs)
def myfind(l,p):
    lr=[];
    #logging.info p
    p1=p.replace(".",r"\.")
    p2=p1.replace("*",".*")
    p2=p2+"$"
    for a in l:
        #logging.info a
        if  re.search(p2,a,re.IGNORECASE)==None :
           pass
           #logging.info "pass"
        else:
           lr.append(a)
       #logging.info "append"
    return lr
if sys.platform == "linux":
    cs0=r"/mnt/chemi/仪器采集/ELTRACSI"
    cs1=r"/mnt/chemi/仪器采集/ELTRACSI_back"
    cs2=r"/mnt/chemi/仪器采集/采集后未删除文件"
    on0=r"/mnt/chemi/仪器采集/caiji/leco_on"
    on1=r"/mnt/chemi/仪器采集/caiji/leco_on_back"
    on2=r"/mnt/chemi/仪器采集/采集后未删除文件"
else:
    cs0 = r"\\10.0.114.230\化学分析室\仪器采集\ELTRACSI"
    cs1 = r"\\10.0.114.230\化学分析室\仪器采集\ELTRACSI_back"
    cs2 = r"\\10.0.114.230\化学分析室\仪器采集\采集后未删除文件"
    on0 = r"\\10.0.114.230\化学分析室\仪器采集\caiji\leco_on"
    on1 = r"\\10.0.114.230\化学分析室\仪器采集\caiji\leco_on_back"
    on2 = r"\\10.0.114.230\化学分析室\仪器采集\采集后未删除文件"
def removeOne(fname,p0,p1,p2):        
    logging.info(fname)
    f=os.path.splitext(fname)
    uploads=mylistdir(p1,f[0]+"*")
    if len(uploads)>0:
        if sys.platform == "linux":
            cmd="mv %s %s" %(os.path.join(p0,fname),p2)
        else:
            cmd="move %s %s" %(os.path.join(p0,fname),p2)
        logging.info(cmd)
        os.system(cmd)
def cs():
    fs=mylistdir(cs0,"*.*")
    for f in fs:
        removeOne(f,cs0,cs1,cs2)
def onh():
    fs=mylistdir(on0,"*.*")
    for f in fs:
        removeOne(f,on0,on1,on2)        
def removeOld():
    cs()
    onh()
class TrayIcon(QtWidgets.QSystemTrayIcon):
    def __init__(self,MainWindow,parent=None):
        super(TrayIcon, self).__init__(parent)
        self.ui = MainWindow
        MainWindow.updated.connect(self.showMsg)
        self.createMenu()
        self.ui.showNormal()
    def remove(self):
        removeOld()
    def createMenu(self):
        self.menu = QtWidgets.QMenu()
        self.showAction1 = QtWidgets.QAction("show", self, triggered=self.show_window)
        self.showAction2 = QtWidgets.QAction("remove captured", self,triggered=self.remove)
        self.showAction3 = QtWidgets.QAction("hide", self, triggered=self.hide_window)
        self.quitAction = QtWidgets.QAction("退出", self, triggered=self.quit)
 
        self.menu.addAction(self.showAction1)
        self.menu.addAction(self.showAction2)
        self.menu.addAction(self.showAction3)
        self.menu.addAction(self.quitAction)
        self.setContextMenu(self.menu)
 
        #设置图标
        self.setIcon(QtGui.QIcon(os.path.join(getpath.getpath(),"work.ico")))
        self.icon = self.MessageIcon()
 
        #把鼠标点击图标的信号和槽连接
        self.activated.connect(self.onIconClicked)
 
    def showMsg(self,msg):
        self.showMessage("Message", msg, self.icon)
 
    def show_window(self):
        #若是最小化，则先正常显示窗口，再变为活动窗口（暂时显示在最前面）
        self.ui.showNormal()
        self.ui.activateWindow()

    def hide_window(self):
        #若是最小化，则先正常显示窗口，再变为活动窗口（暂时显示在最前面）
        self.ui.showMinimized()
 
    def quit(self):
        QtWidgets.qApp.quit()
 
    #鼠标点击icon传递的信号会带有一个整形的值，1是表示单击右键，2是双击，3是单击左键，4是用鼠标中键点击
    def onIconClicked(self, reason):
        if reason == 2 or reason == 3:
            # self.showMessage("Message", "skr at here", self.icon)
            if self.ui.isMinimized() or not self.ui.isVisible():
                #若是最小化，则先正常显示窗口，再变为活动窗口（暂时显示在最前面）
                self.ui.showNormal()
                self.ui.activateWindow()
                self.ui.setWindowFlags(QtCore.Qt.Window)
                self.ui.show()
            else:
                #若不是最小化，则最小化
                self.ui.showMinimized()
                self.ui.setWindowFlags(QtCore.Qt.SplashScreen)
                self.ui.show()
                # self.ui.show()
class MainW(QMainWindow):
    updated = pyqtSignal(str)
    # def contextMenuEvent(self, event):
    #     menu = QMenu(self)
    #     i=0
    #     for one in config_json.setting["apps"]:
    #         oneAction = menu.addAction(one)
    #         oneAction.triggered.connect( lambda boo,val=i: self.openApp(val))
    #         i+=1
    #     action = menu.exec_(self.mapToGlobal(event.pos()))
    def openApp(self,i):
        # logging.info(action,dir(action))
        logging.info(i)
        subprocess.Popen(config_json.setting["apps"][i])
    def closeEvent(self, event):
        config_json.write_setting()
        event.accept()
    def __init__(self, parent=None):
        super().__init__(parent)
        self.ui = ui_mainw.Ui_MainWindow()
        self.ui.setupUi(self)
        self.setWindowIcon(QtGui.QIcon(os.path.join(getpath.getpath(),"work.ico")))
        config_json.read_setting()
        self.setWindowFlags(Qt.WindowStaysOnTopHint)
        self.timer = QTimer(self)
        self.timer.timeout.connect(self.run)
        self.timer.start(10*60*1000)
        self.label=QLabel(self)
        self.txt=""
        self.statusBar().addWidget(self.label)
        # self.button=QPushButton(self)
        # self.button.setText("apps")
        # self.button.clicked.connect(self.show_dlgapp)
        # self.button2=QPushButton(self)
        # self.button2.setText("root")
        # self.button2.clicked.connect(self.button2_pressed)
        # self.statusBar().addWidget(self.button)
        # self.statusBar().addWidget(self.button2)
        self.button_cs=QPushButton(self)
        self.button_cs.setText("cs")
        self.button_cs.clicked.connect(self.button_cs_pressed)
        self.statusBar().addWidget(self.button_cs)
        self.button_on=QPushButton(self)
        self.button_on.setText("on")
        self.button_on.clicked.connect(self.button_on_pressed)
        self.statusBar().addWidget(self.button_on)
        self.action_clip = QtWidgets.QAction(self)
        self.action_clip.setObjectName("action_clip")
        self.action_clip.setText("clip->env")
        self.action_clip.setShortcut("Ctrl+V")
        self.action_clip.triggered.connect(self.clip)
    
        self.action_remove = QtWidgets.QAction(self)
        self.action_remove.setText("remove")
        self.action_remove.triggered.connect(removeOld)
    
        self.model = QtWidgets.QFileSystemModel()
        # self.model.setFilter(QDir.Hidden QDir.Dirs | QDir.Drives | QDir.NoDotAndDotDot | QDir.AllDirs)#QDir.Hidden & QDir. AllDirs)
# 'AccessMask', 'AllDirs', 'AllEntries', 'CaseSensitive', 'Dirs', 'DirsFirst', 'DirsLast', 'Drives', 'Executable', 'Files', 'Filter', 'Filters', 'Hidden', 'IgnoreCase', 'LocaleAware', 'Modified', 'Name', 'NoDot', 'NoDotAndDotDot', 'NoDotDot', 'NoFilter', 'NoSort', 'NoSymLinks', 'PermissionMask', 'Readable', 'Reversed', 'Size', 'SortByMask', 'SortFlag', 'SortFlags', 'System', 'Time', 'Type', 'TypeMask', 'Unsorted', 'Writable'        
        self.model.setFilter(QDir.Hidden | QDir.AllEntries)#QDir.Hidden & QDir. AllDirs)
# filter << "*.jpg" << "*.png" << "*.bmp" << "*.gif";
# model->setNameFilters(filter);        
        
        self.ui_treeView=QtWidgets.QTreeView(self)
        self.ui_treeView.setSortingEnabled(True)
        self.ui_treeView.setModel(self.model)
        self.ui_treeView.doubleClicked.connect(self.startfile)
        self.goto(".")
        self.centralwidget = QtWidgets.QWidget(self)
        self.v=QtWidgets.QVBoxLayout(self.centralwidget)
        self.l=QLineEdit()
        self.l.editingFinished.connect(self.edit_finish)
        self.v.addWidget(self.l)        
        self.v.addWidget(self.ui_treeView)
        self.setCentralWidget(self.centralwidget)
        self.ui_treeView.setContextMenuPolicy(Qt.CustomContextMenu)
        self.ui_treeView.customContextMenuRequested.connect(self.openMenu)
        bar=self.menuBar()
        #向菜单栏中添加新的QMenu对象，父菜单
        file=bar.addMenu('Action')
        if sys.platform == "linux":
            pass
        else:
            file.addAction(self.action_clip)
        file.addAction(self.action_remove)
        self.action_apps = QtWidgets.QAction(self)
        self.action_apps.setText("apps")
        self.action_apps.triggered.connect(self.show_dlgapp)
        file.addAction(self.action_apps)
        i=0
        for one in config_json.setting["apps"]:
            oneAction = QtWidgets.QAction(self)
            oneAction.setText(one)
            oneAction.triggered.connect( lambda boo,val=i: self.openApp(val))
            file.addAction(oneAction)
            i+=1
        quit=QAction('Quit',self)
        file.addAction(quit)
        #单击任何Qmenu对象，都会发射信号，绑定槽函数
        quit.triggered.connect(self.close)

        tb=self.addToolBar('File')
        if sys.platform == "linux":
            pass
        else:
            tb.addAction(self.action_clip)
        tb.addAction(self.action_remove)
        tb.addAction(quit)
        self.run()
    def goto(self,path):
        self.model.setRootPath(path)
        index = self.model.index(path)
        self.ui_treeView.sortByColumn(0, Qt.AscendingOrder)
        self.ui_treeView.setRootIndex(index)
        self.ui_treeView.collapseAll()
        self.ui_treeView.expand(index)      #当前项展开
        self.ui_treeView.scrollTo(index)    #定位到当前项
        self.ui_treeView.setColumnWidth(0,260)
    def openMenu(self, position):
        logging.info("openMenu")
        indexes = self.ui_treeView.selectedIndexes()
        logging.info(indexes)
        if len(indexes) > 0:
            index=indexes[0]
            logging.info(self.model.filePath(index))
            menu = QMenu(self)
            officeAction = menu.addAction("office")
            terminalAction = menu.addAction("terminal")
            exeAction = menu.addAction("exec")
            xdgAction = menu.addAction("xdg")
            sublAction = menu.addAction("subl")
            action = menu.exec_(self.mapToGlobal(position))
            if action == officeAction:
                self.openWithOffice(self.model.filePath(index))
            elif action == terminalAction:
                self.openWithTerminal(self.model.filePath(index))
            elif action == exeAction:
                self.execute(self.model.filePath(index))    
            elif action == xdgAction:
                self.xdg(self.model.filePath(index))
            elif action == sublAction:
                self.subl(self.model.filePath(index))                
            # elif action == usedAction:
            #     self.usedChannel()
            # elif action == allAction:
            #     self.allChannel()
            # elif action == validAction:
            #     self.validChannel()
    def edit_finish(self):
        path=self.l.text()
        logging.info(path)
        if os.path.isdir(path):
            self.goto(path)
        elif os.path.isfile(path):
            info=QtCore.QFileInfo(path)
            if info.isExecutable():
                subprocess.Popen(path)
            else:
                subprocess.Popen(["xdg-open",path])
        else:
            (path,filter)=os.path.split(path)
            logging.info(path,filter)
            if os.path.isdir(path):
                self.goto(path)
                self.model.setNameFilters([filter,]);

    def subl(self,path):
        subprocess.Popen(["subl",path])
    def xdg(self,path):
        logging.info("execute====")
        logging.info(path)
        if os.path.isdir(path):
            pass
        else:
            logging.info("xdg")
            subprocess.Popen(["xdg-open",path])
    def execute(self,path):
        logging.info("execute====")
        logging.info("path")
        if os.path.isdir(path):
            pass
        else:
            logging.info("Popen")
            subprocess.Popen(path)
    def openWithTerminal(self,path):
        logging.info(path)
        if os.path.isdir(path):
            p=path
        else:
            p=os.path.split(path)[0]
        para="--default-working-directory=%s" % p
        subprocess.Popen(["/usr/bin/xfce4-terminal",para])
    def openWithOffice(self,path):
        pass

    def button_cs_pressed(self):
        self.goto(cs0)
    def button_on_pressed(self):
        self.goto(on0)
    def startfile(self, signal):
        logging.info("double clicked",signal)
        file_path=self.model.filePath(signal)
        if os.path.isfile(file_path):
            file_info=self.model.fileInfo(signal)
            if file_info.isExecutable():
                subprocess.Popen(file_path)
                return
            if sys.platform == "linux":
                excel="xdg-open"
                logging.info(excel,file_path)
                subprocess.Popen([excel,file_path])
            else:
                path = r"HKEY_LOCAL_MACHINE\Software\Microsoft\Windows\CurrentVersion\App Paths\EXCEL.EXE"
                setting2 = QSettings(path, QSettings.NativeFormat)
                excel=os.path.join(setting2.value("Path"),"excel.exe")
                file_path=file_path.replace("/","\\")
                logging.info(excel,file_path)
                subprocess.Popen([excel,file_path])
    def button2_pressed(self):
        self.goto("/")
    def clip(self):
        logging.info("clip")
        clipboard = QApplication.clipboard()
        t=clipboard.text()
        logging.info(t)
        if t!="":
            path='HKEY_CURRENT_USER\\Environment'
            setting2 = QSettings(path, QSettings.NativeFormat)
            lines=t.split("\n")
            for l in lines:
                fs=l.split("=")
                if len(fs)==2:
                    logging.info(fs)
                    setting2.setValue(fs[0],fs[1])

    def show_dlgapp(self):
        from DlgApps import DlgArr
        logging.info(config_json.setting)
        ff = config_json.setting["apps"]
        d = DlgArr(ff)
        r = d.exec_()
        if r == 1:
            config_json.setting["apps"]=d.model.todos
            # self.refresh_ff2()
        else:
            pass
    def run(self):
        # try:#OSError
        try:
            txt="%d/%d %d/%d" % (len(os.listdir(cs0)),len(os.listdir(cs1)),len(os.listdir(on0)),len(os.listdir(on1)))
            if txt!=self.txt:
                self.txt=txt
                self.label.setText(txt)
                self.updated.emit(txt)
        except FileNotFoundError:
            pass
        # except OSError:#network not connected
        #     logging.info("OSError==")
        #     pass
    def leftBottom(self):
        self.resize(300,300)
        screen = QDesktopWidget().screenGeometry()
        # 获取窗口坐标系
        size = self.geometry()
        logging.info(size)
        newLeft = 0
        newTop =screen.height() -80-size.height()
        self.move(int(newLeft),int(newTop))
if __name__ == "__main__":
    import sys
    # from qt_material import apply_stylesheet
    import qdarkstyle
    import getpath
    import os
    a = QApplication(sys.argv)
    # apply_stylesheet(a, theme='dark_cyan.xml')    
    a.lastWindowClosed.connect(a.quit)
    dark_stylesheet = qdarkstyle.load_stylesheet_pyqt5()
    a.setStyleSheet(dark_stylesheet)
    w = MainW()
    w.leftBottom()
    ti = TrayIcon(w)
    ti.show()
    # ti.showMsg("test show Message")
    a.exec_()
